package com.draven.socket;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class WebSocketHandler extends TextWebSocketHandler {

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        System.out.println("WebSocket connection established.");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        System.out.println("Received message: " + payload);

        // 模拟一个流式输出的例子
        String response = "Hello, this is a stream of text.";
        sendStream(session, response);
    }

    private void sendStream(WebSocketSession session, String text) throws InterruptedException, IOException {
        for (char c : text.toCharArray()) {
            session.sendMessage(new TextMessage(String.valueOf(c)));
            TimeUnit.MILLISECONDS.sleep(500); // 模拟延迟
        }
    }
}